﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Net.Mail;
using System.Text;
using System.Collections.Specialized;
using DAO;
using DVO;

public partial class UploadDocument : System.Web.UI.Page
{
    public int _Id = 0;
    public int _WID = 0;
    protected void Page_Load(object sender, EventArgs e)
    {
        if (Page.User.Identity.Name=="")
        {
            Response.Redirect("Login.aspx");
        }
        else
        {
            if (!String.IsNullOrEmpty(Request.QueryString["Id"]))
            {
                _Id = Convert.ToInt32(Request.QueryString["Id"].ToString());
            }
            if (!String.IsNullOrEmpty(Request.QueryString["WId"]))
            {
                _WID = Convert.ToInt32(Request.QueryString["WId"].ToString());
            }
            if (IsPostBack == false)
            {
                if (_Id > 0)
                {
                    LoadInfo(_Id);
                    LoadMember();
                    LoadMemberManage();
                    hidebutton();
                }
                if (_WID > 0)
                {
                    LoadDocumentInfo(_WID);
                }
            }
        }
       

    }

    #region "Upload"
    public void UpLoad()
    {
        string email = "";
        int x = 0;
        foreach (ListItem item in CheckBoxList2.Items)
        {
            if (item.Selected == true)
            {
                x = x + 1;
                email +=  item.Value + ";";
            }
        }
        //String [] adrr=email.Split(';');

        if (x == 0)
        {
            ShowMessage("Chưa chọn người quản lý để gửi mail!");
            return;
        }
        email = email.Substring(0, email.Length - 1);
        if (txtDocumentName.Text == "")
        {
            ShowMessage("Vui lòng điền tên tài liệu");
            return;
        }
        Document objDoc = new Document();
        objDoc.Status = 0;
        objDoc.DocumentName = txtDocumentName.Text.Trim();
        objDoc.WorkId = Convert.ToInt32(hdfWordId.Value);
        objDoc.Notes = txtNotes.Text.Trim();
        // Upload Tài Liệu
        string Floder = string.Format("{0}/{1}/{2}", DateTime.Now.Year, DateTime.Now.Month, DateTime.Now.Day);
        string sPhysicalPath = Server.MapPath("~/" + Common.UPLOAD_DOCUMENT_PATH);
        string sPhysicalPathImage = string.Format("{0}/{1}", sPhysicalPath, Floder);
        //' check directory
        if ((!System.IO.Directory.Exists(sPhysicalPathImage)))
        {
            System.IO.Directory.CreateDirectory(sPhysicalPathImage);
        }

        if ((DocumentFileFileUpload.PostedFile != null) & (DocumentFileFileUpload.PostedFile.ContentLength > 0))
        {
            string sFileName = System.IO.Path.GetFileName(DocumentFileFileUpload.PostedFile.FileName);
            try
            {
                string sFileType = "";
                sFileType = sFileName.Substring(sFileName.LastIndexOf(".") + 1, sFileName.Length - sFileName.LastIndexOf(".") - 1).ToLower();
                if ((sFileType != "docx" & sFileType != "doc"))
                {
                    ShowMessage("Định dạng file được upload: docx, doc. Chọn lại file cần upload.");
                    return;
                }

                sFileName = string.Format("{0}_{1}{2}{3}{4}.{5}", Common.GetKeyWord(txtDocumentName.Text.Trim()), DateTime.Now.Day, DateTime.Now.Hour, DateTime.Now.Minute, DateTime.Now.Second, sFileType);
                DocumentFileFileUpload.SaveAs(sPhysicalPathImage + "/" + sFileName);
                objDoc.LinkDocument = "Document" + "/" + Floder + "/" + sFileName;
            }
            catch (Exception ex)
            {
                Common.WriteLog(ex.Message, ex.StackTrace);
            }
        }
        else
        {
            if (hdfLinkDocument.Value == "")
            {
                ShowMessage("Chưa chọn tài liệu kiểm duyệt");
                return;
            }
        }

        BLL_Document ObjBll = new BLL_Document();
        int IdReturn = ObjBll.Document_Insert(objDoc);
        if (IdReturn > 0)
        {
            BLL_Approve ObjApprove = new BLL_Approve();
            int y = 0;
            foreach (ListItem item in CheckBoxList1.Items)
            {
                if (item.Selected == true)
                {
                    if (ObjApprove.Approve_Insert(IdReturn, item.Text, 0) > 0)
                    {
                        y = y + 1;
                    }
                }
            }
            if (y > 0)
            {
                if (ckbAttach.Checked == true)
                {
                    if (EmailHelper.SendNewMessage(Server.MapPath("~/Resources/Template"), email, "1", IdReturn) == true)
                    {
                        ShowMessage("Gửi tài liệu thành công");
                        return;
                    }
                    else
                    {
                        ShowMessage("Gửi tài liệu thành công");
                        return;
                    }
                }
                else
                {
                    if (EmailHelper.SendNewMessage(Server.MapPath("~/Resources/Template"), email, "", IdReturn) == true)
                    {
                        ShowMessage("Gửi tài liệu thành công");
                        return;
                    }
                    else
                    {
                        ShowMessage("Gửi tài liệu thành công");
                        return;
                    }
                }
            }
        }
        else
        {
            ShowMessage("Có lỗi xảy ra trong lúc gửi tài liệu");
            return;
        }
    }

    #endregion

    #region "funtion"
    protected void Button1_Click(object sender, EventArgs e)
    {
        UpLoad();

    }
    #endregion

    #region "LoadData"
    private void LoadInfo(int Id)
    {
        BLL_Working ObjBLL = new BLL_Working();
        ins_Working_SelectByIdResult ObjList = new ins_Working_SelectByIdResult();
        try
        {
            if (ObjList != null)
            {
                ObjList = ObjBLL.Working_SelectById(Id);
                txtNotes.Text = ObjList.Notes;
                txtWorkName.Text = ObjList.WorkName;
                //Linkdocument.Visible = true;
                hdfWordId.Value = ObjList.Id.ToString();
                txtToDate.Text = string.Format("{0: dd/MM/yyy}", ObjList.ToDate);
                txtFromDate.Text = string.Format("{0: dd/MM/yyy}", ObjList.CreateDate);
                //ddlStatus.SelectedValue = ObjList.Status.ToString();
            }
        }
        catch (Exception ex)
        {
            Common.WriteLog(ex.Message, ex.StackTrace);
        }
       
    }
    private void LoadMember()
    {
        BLL_Member ObjBLL = new BLL_Member();
        List<ins_Member_SelectLevelResult> ObjList = new List<ins_Member_SelectLevelResult>();
        try
        {
            ObjList = ObjBLL.Level_Select(3).ToList();
            CheckBoxList1.DataSource = ObjList;
            CheckBoxList1.DataTextField = "UserName";
            CheckBoxList1.DataValueField = "Id";
            CheckBoxList1.DataBind();
        }
        catch (Exception ex) 
        {
            Common.WriteLog(ex.Message, ex.StackTrace);
        }

    }
    private void LoadMemberManage()
    {
        BLL_Member ObjBLL = new BLL_Member();
        List<ins_Member_SelectLevelResult> ObjList = new List<ins_Member_SelectLevelResult>();
        try
        {
            ObjList = ObjBLL.Level_Select(2).ToList();
            CheckBoxList2.DataSource = ObjList;
            CheckBoxList2.DataTextField = "UserName";
            CheckBoxList2.DataValueField = "Email";
            CheckBoxList2.DataBind();
        }
        catch (Exception ex)
        {
            Common.WriteLog(ex.Message, ex.StackTrace);
        }

    }

    private void LoadDocumentInfo(int id)
    {
        BLL_Document ObjBLL = new BLL_Document();
        ins_Document_SelectByIdResult ObjList = new ins_Document_SelectByIdResult();
        ObjList = ObjBLL.Document_SelectById(id);
        txtDocumentName.Text = ObjList.DocumentName;
        txtNotes.Text = ObjList.Notes;
        txtWorkName.Text = ObjList.WorkName;
        //Linkdocument.Visible = true;
        //Linkdocument.HRef = ObjList.LinkDocument;
    }
    #endregion

    #region "Show message"
    private string ShowMessage(string message)
    {
      return lbmessage.Text = message;
    }
    #endregion

    private void hidebutton()
    {
        txtNotes.ReadOnly = true;
        txtWorkName.ReadOnly = true;
        txtFromDate.ReadOnly = true;
        txtToDate.ReadOnly = true;
    }

}
